#!/bin/bash
set -CeEu
set -o pipefail

SPATH="$(readlink -f "$0")"
SDIR="$(dirname "${SPATH}")"; export SDIR;
SCRIPT_NAME="${0##*/}"

# shellcheck source=common.sh
. "${SDIR}/common.sh"

cd "${SDIR}"

verify_template_instance_with_source_image() {
  local image_project="${1:-debian-cloud}"
  local image_family="${2:-debian-10}"

  create_source_instance_template "${image_project}" "${image_family}"

  CREATE_FROM_SOURCE=1
  create_new_instance_template "${SOURCE_INSTANCE_TEMPLATE_NAME}" "vm-${LT_NAMESPACE}"; RETVAL=$?;
  trap 'delete_instance_template "${SOURCE_INSTANCE_TEMPLATE_NAME}"' ERR

  INSTANCE_TEMPLATE_NAME="vm-${LT_NAMESPACE}"
  verify_instance_template_with_source

  delete_instance_template "${INSTANCE_TEMPLATE_NAME}"
  delete_instance_template "${SOURCE_INSTANCE_TEMPLATE_NAME}"
}

verify_template_instance_with_custom_image() {
  create_custom_source_instance_template

  CREATE_FROM_SOURCE=1
  create_new_instance_template "${CUSTOM_SOURCE_INSTANCE_TEMPLATE_NAME}" "${CUSTOM_INSTANCE_TEMPLATE_NAME}"; RETVAL=$?;
  trap 'delete_instance_template "${CUSTOM_SOURCE_INSTANCE_TEMPLATE_NAME}"' ERR

  INSTANCE_TEMPLATE_NAME="${CUSTOM_INSTANCE_TEMPLATE_NAME}"
  verify_instance_template_with_source

  delete_instance_template "${CUSTOM_SOURCE_INSTANCE_TEMPLATE_NAME}"
  delete_instance_template "${CUSTOM_INSTANCE_TEMPLATE_NAME}"
  gcloud compute images delete "${CUSTOM_IMAGE_NAME}" \
  --project "${PROJECT_ID}" --quiet
}

verify_default_template_instance() {
  create_new_instance_template "${SOURCE_INSTANCE_TEMPLATE_NAME}" "vm-${LT_NAMESPACE}"; RETVAL=$?;
  trap 'cleanup_workload_service_account' ERR
  INSTANCE_TEMPLATE_NAME="vm-${LT_NAMESPACE}"
  verify_instance_template
  delete_instance_template "${INSTANCE_TEMPLATE_NAME}"
}

main() {
  # CLI setup
  parse_args "$@"

  run_basic_test "install" "mesh_ca" "-o vm -o hub-meshca --enable_gcp_components --enable_registration"; RETVAL=$?;
  trap 'cleanup_lt_cluster "${LT_NAMESPACE}" "${OUTPUT_DIR}" "${REV}"' ERR

  create_workload_service_account

  echo "Applying WorkloadGroup ${WORKLOAD_NAME} in namespace ${LT_NAMESPACE}..."
  kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: WorkloadGroup
metadata:
  name: ${WORKLOAD_NAME}
  namespace: ${LT_NAMESPACE}
spec:
  metadata:
    annotations:
      security.cloud.google.com/IdentityProvider: google
    labels:
      app: ${WORKLOAD_NAME}
      version: v1
  template:
    serviceAccount: ${WORKLOAD_SERVICE_ACCOUNT}
EOF

  verify_default_template_instance
  verify_template_instance_with_source_image
  verify_template_instance_with_source_image "centos-cloud" "centos-8"
  verify_template_instance_with_source_image "centos-cloud" "centos-7"
  verify_template_instance_with_custom_image

  cleanup_workload_service_account
  kubectl delete workloadgroup "${WORKLOAD_NAME}" -n "${LT_NAMESPACE}"
  cleanup_lt_cluster "${LT_NAMESPACE}" "${OUTPUT_DIR}" "${REV}"
  delete_service_mesh_feature
}

main "$@"
